'''
fuction : 与服务器建立连接
author  : 辛天宇
data    : 2024-4-9
-------------------------------
author data  modify

'''
import socket  
  
server_ip   = '192.168.5.110'
server_port = 8888 

# 设置服务器地址和端口  
server_address = (server_ip, server_port)
  
# 创建一个socket对象  
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  
# 连接到服务器  
try:  
    client_socket.connect(server_address)  
    print(f'Connected to {server_address}')  
  
    # 接收用户输入并发送给服务器  
    while True:  
        try:  
            user_input = input('Enter command (or "exit" to quit): ')  
            if user_input.lower() == 'exit':
                cmd = 'Q'
                client_socket.sendall(cmd.encode())
                break
            while 'Q' == user_input:
                print(f'please input other string')
                user_input = input('Enter command (or "exit" to quit): ')
            client_socket.sendall(user_input.encode())  
  
            # 接收服务器的响应
            data = client_socket.recv(512)  
            print(f'Received: {data.decode()}')  
  
        except KeyboardInterrupt:  
            print('\nKeyboardInterrupt received, exiting...')  
            break  
        except ConnectionResetError:  
            print('\nConnection reset by server, exiting...')  
            break  
        except Exception as e:  
            print(f'An error occurred: {e}, trying to reconnect...')  
            client_socket.close()  # Close the socket if there's an error  
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create a new one  
            client_socket.connect(server_address)  # Reconnect to the server  
  
finally:  
    # 关闭连接  
    print('Closing socket')  
    client_socket.close()